<template>
  <el-dialog style="margin-top: 99px!important;height: 75%!important;" title="选择地图位置" v-model="open" width="65%" height="65%" append-to-body>
      <el-row>
          <el-col :span="6">
              <el-input
                  v-model="cityName"
                  placeholder="请输入地点名称"
                  clearable
                  prefix-icon="Search"
                  style="width: 90%;"
                  @change="selectPosition"
              />
          </el-col>
          <el-col :span="4">
              <el-button type="danger" icon="Search" @click="selectPosition">查询</el-button>
              <el-button icon="Refresh" @click="resetPosition">重置</el-button>
          </el-col>
          <el-col :span="14">
            <div style="text-align: right;margin-top: 10px;margin-right: 10px;font-weight: bold;">
              当前经度:{{lngValue!== '' && lngValue!== null && lngValue!== undefined? lngValue : ''}} &nbsp;&nbsp;
              当前纬度:{{latValue!== '' && latValue!== null && latValue!== undefined? latValue : ''}}
            </div>
          </el-col>
      </el-row>    

      <div style="margin-top: 20px;">
        <div id="baidu-location-map" class="bm-view"></div>
        <div id="r-result" class="select-result"></div>
      </div>
      
      <el-divider  style="margin: 15px 0px 0px 0px; border-top : 1px solid #e8e8e8;"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPosition">确 定</el-button> 
          <el-button @click="cancelPosition">取 消</el-button>
        </div>
      </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";

  const props = defineProps({
    parentMethod: {
      type: Function,
      required: true,
      default: () => {}
    }
  })
  const open = ref(false);
  const centerPoint = ref(null);
  const cityName = ref("");
  const lngValue = ref("");
  const latValue = ref("");
  const centerLngValue = ref("");
  const centerLatValue = ref("");
  const zoomValue = ref(18);
  const map = ref(null);
  const localsearch = ref(null);
  const showPosition = (position) => {
    if (position!== null && position!== undefined){
      centerPoint.value = position;
      lngValue.value = position.lng;
      latValue.value = position.lat;
      centerLngValue.value = position.centerLng;
      centerLatValue.value = position.centerLat;
      zoomValue.value = position.zoom;
      setTimeout(() => {
        initMapLocation(centerPoint.value);
      }, 1);
    }
    open.value = true;
  };

  defineExpose({
    showPosition
  });

  // 初始化定位地图标注
  function initMapLocation(ctPoint) {
      // 创建地图实例
      map.value = new T.Map("baidu-location-map"); // 版本3的构造函数名是T.Map

      var middlePoint = new T.LngLat(ctPoint.centerLng, ctPoint.centerLat); // 创建点坐标
      map.value.centerAndZoom(middlePoint, ctPoint.zoom); // 初始化地图，设置中心点坐标和地图级别

      //创建对象
      var ctrl = new T.Control.MapType();
      //添加控件
      map.value.addControl(ctrl);

      //创建缩放平移控件对象
      var control = new T.Control.Zoom();
      control.setPosition(T_ANCHOR_BOTTOM_RIGHT);
      //添加缩放平移控件
      map.value.addControl(control);

      let tmpPoint = new T.LngLat(ctPoint.lng, ctPoint.lat); // 创建点坐标
      let marker = new T.Marker(tmpPoint);  // 创建标注
      map.value.addOverLay(marker);               // 将标注添加到地图中

      var cp = new T.CoordinatePickup(map.value, {callback: getLngLat})
      cp.addEvent();

      var config = {
          pageCapacity: 10,	//每页显示的数量
          onSearchComplete: localSearchResult	//接收数据的回调函数
      };
      //创建搜索对象
      localsearch.value = new T.LocalSearch(map.value, config);
  }

  // 点击事件
  function getLngLat(lnglat) {
      // 清除标注
      map.value.clearOverLays();
      // 创建标注
      var tmpLng = lnglat.lng.toFixed(6);
      var tmpLat = lnglat.lat.toFixed(6);
      let tmpPoint = new T.LngLat(tmpLng, tmpLat);
      let marker = new T.Marker(tmpPoint);
      map.value.addOverLay(marker);      // 将标注添加到地图中
      // 向父类传递数据
      setCenterPointData(lnglat);
  }

  // 传递数据
  function setCenterPointData(point) {
      var tmpLng = point.lng.toFixed(6);
      var tmpLat = point.lat.toFixed(6);

      // 获取地图中心点坐标
      var centerPoint = map.value.getCenter();
      var centerLngValue = centerPoint.lng.toFixed(6);
      var centerLatValue = centerPoint.lat.toFixed(6);

      // 获取缩放级别
      var zoomValue = map.value.getZoom().toFixed(0);

      // 调用设置中心点数据方法
      callBackMapPosition(tmpLng, tmpLat, centerLngValue, centerLatValue, zoomValue);
  }

  // 根据城市名称定位地图中心点
  function locateByCityName(cityName) {
    localsearch.value.search(cityName);
  }

  //接收数据的回调函数
  function localSearchResult(result) {
      //清空地图及搜索列表
      clearAllOverlays();

      //解析行政区划边界
      area(result.getArea());
  }

  //解析行政区划边界
  function area(obj) {
    if (obj) {
      if(obj.points){
        //坐标数组，设置最佳比例尺时会用到
            var pointsArr = [];
            var points = obj.points;
            for (var i = 0; i < points.length; i++) {
                var regionLngLats = [];
                var regionArr = points[i].region.split(",");
                for (var m = 0; m < regionArr.length; m++) {
                    var lnglatArr = regionArr[m].split(" ");
                    var lnglat = new T.LngLat(lnglatArr[0], lnglatArr[1]);
                    regionLngLats.push(lnglat);
                    pointsArr.push(lnglat);
                }
                //创建线对象
                var line = new T.Polyline(regionLngLats, {
                    color: "blue",
                    weight: 3,
                    opacity: 1,
                    lineStyle: "dashed"
                });
                //向地图上添加线
                map.value.addOverLay(line);
            }
            //显示最佳比例尺
            map.value.setViewport(pointsArr);
      }
      if(obj.lonlat){
        var regionArr = obj.lonlat.split(",");
        map.value.panTo(new T.LngLat(regionArr[0], regionArr[1]));
      }
    }
  }

  // 清除所有覆盖物
  function clearAllOverlays() {
      map.value.clearOverLays();
  }
  
  //重置
  function resetPosition() {
    cityName.value = "";
    lngValue.value = "";
    latValue.value = "";
    centerLngValue.value = "";
    centerLatValue.value = "";
    zoomValue.value = 18;
    clearAllOverlays();
  }

  // 查询
  function selectPosition() {
    if (cityName.value) {
      locateByCityName(cityName.value);
    }else {
      alert("请输入地点名称！");
    }
  }

  // 确定按钮
  function submitPosition() {
    props.parentMethod(lngValue.value, latValue.value, centerLngValue.value, centerLatValue.value, zoomValue.value);
    open.value = false;
  }

  // 取消按钮
  function cancelPosition() {
    resetPosition();
    open.value = false;
  }

  
  // 设置中心点数据方法
  function callBackMapPosition(lng, lat, centerLng, centerLat, zoom) {
    lngValue.value = lng;
    latValue.value = lat;
    centerLngValue.value = centerLng;
    centerLatValue.value = centerLat;
    zoomValue.value = zoom;
  }
</script>
<style lang="scss" scoped>
.bm-view {
    width: 100%;
    height: 500px; /* 必须设置宽高 */
    z-index: 99999999!important;
}
.select-result {
    position: absolute;
    top: 92px;
    left: 16px;
    width: 275px;
    z-index: 99999999!important;
}
.red-marker img {
  filter: hue-rotate(0deg) saturate(5);  /* 调整为红色 */
}
</style>